package com.ybbase.framework.controller.system;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ybbase.framework.base.model.TreeMessage;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.enums.LogFunType;
import com.ybbase.framework.common.enums.LogType;
import com.ybbase.framework.common.util.BeanUtil;
import com.ybbase.framework.model.po.system.OrganUser;
import com.ybbase.framework.model.po.system.Role;
import com.ybbase.framework.service.system.LogService;
import com.ybbase.framework.service.system.PermissionService;
import com.ybbase.framework.service.system.PostService;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import com.ybbase.framework.model.po.system.Post;
import javafx.geometry.Pos;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RestController;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.service.system.OrganizationService;
import com.ybbase.framework.model.po.system.Organization;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParams;
import com.ybbase.framework.base.model.ResponseBean;

import javax.servlet.http.HttpServletRequest;

/**
 * 系统机构 前端控制器
 *
 * @author cg
 * @since 2019-11-25
 * 云平台2.0
 */
@RestController
@RequestMapping(value = "/organization", produces = {"application/json;charset=UTF-8"})
@Api("系统机构")
public class OrganizationController extends BaseController {

    private static final Logger LOGGER = LogManager.getLogger(OrganizationController.class);

    @Autowired
    private OrganizationService targetService;


    @Autowired
    private PermissionService permissionService;


    @Autowired
    private PostService postService;

    @Autowired
    private LogService logService;


    /**
     * 系统机构分页查询
     *
     * @param pageIndex 页数
     * @param step      每页数量
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/list")
    @ApiOperation(value = "系统机构分页查询", notes = "系统机构分页查询", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页行数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "organization", value = "系统机构", dataType = "Organization对象")
    })
    public ResponseBean findListByPage(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, Organization organization) {
        try {
            QueryWrapper<Organization> queryWrapper = new QueryWrapper<Organization>();
            if (organization.getParentId() != null && organization.getParentId() != 0) {
                queryWrapper.lambda().eq(Organization::getParentId, organization.getParentId());
            }
            queryWrapper.orderBy(true, true, "parent_id,sort");
            Page<Organization> page = new Page(pageIndex, step);
            if (StringUtils.isNotEmpty(organization.getName())) {
                queryWrapper.lambda().eq(Organization::getName, organization.getName());
            }
            targetService.page(page, queryWrapper);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统机构分页查询" + CommonResultCode.SUCCESS.getMsg(), page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构分页查询异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统机构分页查询" + CommonResultCode.FAIL.getMsg());
        }
    }


    /**
     * 系统机构获取全部数据
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/all")
    @ApiOperation(value = "系统机构获取全部数据", notes = "系统机构获取全部数据")
    public ResponseBean findAll(HttpServletRequest request) {
        TreeMessage treeMessage = new TreeMessage();
        try {
            String tokens = getTokenString(request);
            Integer isAdmin = this.getIsAdmin(tokens);
            List<Organization> models = new ArrayList<>();
            if (isAdmin == 1) {
                QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
                queryWrapper.orderByAsc("parent_id", "sort");
                models = targetService.list(queryWrapper);
            } else {
                QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
                String organs = getDrillOrganString(tokens);
                organizationQueryWrapper.inSql("id", organs);
                organizationQueryWrapper.orderByAsc("parent_id", "sort");
                models = targetService.list(organizationQueryWrapper);
            }
            treeMessage.setCode("200");
            treeMessage.setMessage("系统机构获取全部数据" + CommonResultCode.SUCCESS.getMsg());
            return new ResponseBean(treeMessage, targetService.getOrganTree(models));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构获取全部数据异常：{}", e.getMessage());
            treeMessage.setCode("400");
            treeMessage.setMessage("系统机构获取全部数据" + CommonResultCode.SUCCESS.getMsg());
            return new ResponseBean(treeMessage, new ArrayList<>());
        }
    }

    /**
     * 系统机构根据ID查找数据
     *
     * @param id 唯一编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/find")
    @ApiOperation(value = "系统机构根据ID查找数据", notes = "系统机构根据ID查找数据")
    @ApiImplicitParam(required = true, name = "id", value = "唯一编码", dataType = "Long")
    public ResponseBean find(@RequestParam("id") Long id) {
        try {
            Organization organization = targetService.getById(id);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "操作异常代码配置根据ID查找数据" + CommonResultCode.SUCCESS.getMsg(), organization);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构根据ID查找数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统机构根据ID查找数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统机构保存数据
     *
     * @param organization 系统机构
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PostMapping("/save")
    @ApiOperation(value = "系统机构保存数据", notes = "系统机构保存数据")
    @ApiImplicitParam(required = true, name = "organization", value = "系统机构", dataType = "Organization对象")
    public ResponseBean save(HttpServletRequest request) {
        try {
            QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
            BeanUtil beanUtil = new BeanUtil();
            Organization organization = (Organization) beanUtil.mapToObject(request.getParameterMap(), Organization.class);
            if (organization.getCode() != null && organization.getId() == null) {
                Organization organ = targetService.getOne(queryWrapper.lambda().eq(Organization::getCode, organization.getCode()));
                if (organ != null) {
                    return new ResponseBean(CommonResultCode.FAIL.getCode(), "机构编码已存在保存" + CommonResultCode.FAIL.getMsg(), organ);
                }
            }
            targetService.saveOrUpdateOrganization(organization);
            logService.saveLog(LogType.add.getEnumKey(), LogFunType.office.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统机构保存数据" + CommonResultCode.SUCCESS.getMsg(), organization);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构保存数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统机构保存数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统机构保角色数据
     *
     * @param
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PostMapping("/saveRole")
    @ApiOperation(value = "系统机构保角色数据", notes = "系统机构保存数据")
    @ApiImplicitParam(required = true, name = "organization", value = "系统机构", dataType = "Organization对象")
    public ResponseBean saveRole(@RequestBody Map<String, Integer> param) {
        try {
            try {
                targetService.saveRole(param.get("organizationId"), param.get("roleId"));
            } catch (Exception e) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "此机构已添加当前角色");
            }
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统机构保存角色数据" + CommonResultCode.SUCCESS.getMsg(), param);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构保存数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统机构保存数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统机构更新数据
     *
     * @param organization 系统机构
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PutMapping("/update")
    @ApiOperation(value = "系统机构更新数据", notes = "系统机构更新数据")
    @ApiImplicitParam(required = true, name = "organization", value = "系统机构", dataType = "Organization对象")
    public ResponseBean update(@RequestBody Organization organization) {
        try {
            targetService.updateById(organization);
            logService.saveLog(LogType.edit.getEnumKey(), LogFunType.office.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "操作异常代码配置更新数据" + CommonResultCode.SUCCESS.getMsg(), organization);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构更新数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "操作异常代码配置更新数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统机构删除数据
     *
     * @param
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/del")
    @ApiOperation(value = "系统机构删除数据", notes = "系统机构删除数据")
    @ApiImplicitParam(required = true, name = "id", value = "批量删除数据", dataType = "List<Long>")
    public ResponseBean del(@RequestParam("id") String id) {
        try {
            Organization organization = targetService.getById(Integer.parseInt(id));
            List<Organization> list = targetService.getOrgListByPath(organization.getPath());
            if (list != null && !list.isEmpty()) {
                if (!id.equals(list.get(0).getId() + "")) {
                    return new ResponseBean(CommonResultCode.FAIL.getCode(), "无法删除该组织机构，因为该组织机构下还有子机构！");
                }
            }
            List<OrganUser> organUserList = targetService.getOrganUserByOrgId(id);
            if (organUserList != null && !organUserList.isEmpty()) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "无法删除该组织机构，因为该组织机构下被分配人员！");
            }
            targetService.removeById(id);
            logService.saveLog(LogType.del.getEnumKey(), LogFunType.office.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统机构删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构删除数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统机构删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统机构角色删除数据
     *
     * @param
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PostMapping("/delRole")
    @ApiOperation(value = "系统机构角色删除数据", notes = "系统机构角色删除数据")
    @ApiImplicitParam(required = true, name = "ids", value = "批量删除数据", dataType = "List<Long>")
    public ResponseBean delRole(@RequestBody Map<String, String> param) {
        try {
            targetService.removeRoleById(param.get("organizationId"), param.get("roleId"));
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统机构删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统机构删除数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统机构删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 获取机构树
     *
     * @return ResponseBean
     * @author jzw
     * @date 2019/12/4 9:44
     * @since cloud2.0
     */
    @GetMapping("/orgTree")
    @ApiOperation(value = "机构树", notes = "机构树")
    public ResponseBean findOrgTree() {
        try {
            List<Organization> models = targetService.list();
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "机构树" + CommonResultCode.SUCCESS.getMsg(), targetService.getOrganTree(models));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("机构树获取异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "机构树" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 获取机构下的角色
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/role")
    @ApiOperation(value = "获取机构下的角色", notes = "获取机构下的角色")
    public ResponseBean findListByPage(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, int id) {
        try {
            Page<Role> page = targetService.getOrganRoleListById(id, pageIndex, step);

            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色获取全部数据" + CommonResultCode.SUCCESS.getMsg(), page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色获取全部数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统角色获取全部数据" + CommonResultCode.FAIL.getMsg());
        }
    }


    /**
     * 保存机构和岗位的关系
     *
     * @param organization 机构对象
     * @return ResponseBody
     * @author jzw
     * @date 2019/12/4 21:31
     * @since cloud2.0
     */
    @PostMapping("/saveOrganPost")
    @ApiOperation(value = "保存机构和岗位的关系", notes = "保存机构和岗位的关系")
    @ApiImplicitParam(required = true, name = "Organization", value = "机构信息", dataType = "Organization对象")
    public ResponseBean saveOrganPost(@RequestBody Organization organization) {
        try {
            targetService.saveOrganPost(organization.getId(), organization.getPostList());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "保存机构和岗位关系成功" + CommonResultCode.SUCCESS.getMsg());

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("保存机构和岗位关系:{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "保存机构和岗位关系失败：" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 查询指定机构下的岗位列表
     *
     * @param id 机构ID
     * @return ResponseBean
     * @author jzw
     * @date 2019/12/4 21:55
     * @since cloud2.0
     */
    @GetMapping("/findOrganPostList")
    @ApiOperation(value = "查询指定机构下的岗位列表", notes = "查询指定机构下的岗位列表")
    @ApiImplicitParam(required = true, name = "id", value = "机构ID", dataType = "Int")
    public ResponseBean findOrganPostList(@RequestParam("id") int id) {
        try {
            List<Post> posts = targetService.getOrganPostList(id);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "查询指定机构下的岗位列表成功" + CommonResultCode.SUCCESS.getMsg(), posts);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询指定机构下的岗位列表失败：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "查询指定机构下的岗位列表失败" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 删除指定机构下的岗位关系
     *
     * @param organization 机构对象
     * @return ResponseBean
     * @author jzw
     * @date 2019/12/4 22:15
     * @since cloud2.0
     */
    @DeleteMapping("/delOrganPost")
    @ApiOperation(value = "删除指定机构下的岗位关系", notes = "删除指定机构下的岗位关系")
    @ApiImplicitParam(required = true, name = "Organization", value = "机构信息", dataType = "Organization对象")
    public ResponseBean delOrganPost(@RequestBody Organization organization) {
        try {
            targetService.deleteOrganPost(organization.getId(), organization.getPostList());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "删除指定机构下的岗位关系成功" + CommonResultCode.SUCCESS.getMsg());

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除指定机构下的岗位关系失败：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "删除指定机构下的岗位关系失败：" + CommonResultCode.FAIL.getMsg());
        }

    }

    private Page<Role> getPermission(Page<Role> page) {
        List<Role> Roles = page.getRecords();
        for (Role Role : Roles) {
            Role.setPermissionList(permissionService.getPermissionByRoleId(Role.getId()));
        }
        page.setRecords(Roles);
        return page;
    }

    /**
     * 查询联社列表
     *
     * @param type 类别：联社为1
     * @return
     * @author cg
     * @date 2020-01-01 07:27
     * @since cloud2.0
     */
    @GetMapping("/findOrganListByType")
    public ResponseBean findOrganListByType(Integer type, HttpServletRequest request) {
        String token = getTokenString(request);
        Integer isAdmin = this.getIsAdmin(token);
        List<Organization> list = new ArrayList<>();
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        //if (isAdmin == 1) {
        queryWrapper.lambda().eq(Organization::getType, type);
        list = targetService.list(queryWrapper);
        //} else {
        //    queryWrapper.lambda().eq(Organization::getId, this.getOrganLsByUserId(token));
        //    queryWrapper.lambda().eq(Organization::getType, type);
        //    list = targetService.list(queryWrapper);
        //}
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "查询联社列表" + CommonResultCode.SUCCESS.getMsg(), list);
    }

    /**
     * 根据联社ID查询分行列表
     *
     * @param type     类别：分行社为2
     * @param parentId 上级编码
     * @return
     * @author cg
     * @date 2020-01-01 10:52
     * @since cloud2.0
     */
    @GetMapping("/findOrganListByLid")
    public ResponseBean findOrganListByLid(Integer parentId, Integer type, HttpServletRequest request) {
        String token = getTokenString(request);
        Integer isAdmin = this.getIsAdmin(token);
        List<Organization> list = new ArrayList<>();
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        if (parentId != null) {
            queryWrapper.lambda().eq(Organization::getParentId, parentId);
        }
        //if (isAdmin == 1) {
        queryWrapper.lambda().eq(Organization::getType, type);
        list = targetService.list(queryWrapper);
        //} else {
        //    queryWrapper.lambda().eq(Organization::getId, this.getOrganZhByUserId(token));
        //    queryWrapper.lambda().eq(Organization::getType, type);
        //    list = targetService.list(queryWrapper);
        //}
        return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "查询分行列表" + CommonResultCode.SUCCESS.getMsg(), list);
    }

}

